//
//  QianliInviteDetail.swift
//  todoios
//
//  Created by qianli on 2025/4/22.
//

import Foundation
import UIKit

class QianliInviteDetail: QianliParentNaviVC {
    private var SC6UBWD47fXYWAU3:[InviteDurationModel]=[]
    private var _iPageNum:Int = 1
    private var _iPageTotal:Int = 1
    private var qbYzOWtOn9x9CQkk:Bool = false
    private var yDCfMxMjoZSqnqxo:RetryNet?
    private var YSgwxXklgw9hk52r:MBProgressHUD?
    private var pxKiSZFNBBoSMWU3 = UIRefreshControl()
    private var X4MlDl1WbtyrOkzs = false
    private let RF7NlUOk3CS8x58m = UILabel()
    private let brzwDc3ZHa8Rmucg = UIActivityIndicatorView(style: .medium)
    
    lazy var inviteTable: UITableView = {
        let table = UITableView()
        return table
    }()
    
    deinit {
        QianliUniversalFunc.QianliLog("------QianliInviteDetail.deinit")
    }
     
    override func aB7kFqI8MB6DRPQC() {
        if(!self.qbYzOWtOn9x9CQkk){
            self.yeUFPjBQnL6UZxSA()
        }
    }
    
    override func GHL4Rhb91XYBer27() {
        self.zdMpsGrNncVEHdYA(title:LocalizedString("My Invitation") ) //"我推荐的好友"
        
        view.addSubview(self.inviteTable)
        inviteTable.frame = CGRect(x: 0, y: topSpace+15, width: qianli_pm_width, height: qianli_pm_height - topSpace - 15)
        inviteTable.delegate = self
        inviteTable.dataSource = self
        inviteTable.separatorStyle = .none
        inviteTable.register(InviteDurationCell.self, forCellReuseIdentifier: "InviteDurationCell")
        inviteTable.backgroundColor = .secondarySystemBackground
        // 设置下拉刷新
        self.pxKiSZFNBBoSMWU3.addTarget(self, action: #selector(mhMtQtSTyofwGqyE), for: .valueChanged)
        inviteTable.refreshControl = self.pxKiSZFNBBoSMWU3
        gZk5cuoJMRAV2npo()
    }
    
    override func clFi25NuDNbscWXL() {
        if let hud = self.YSgwxXklgw9hk52r{
            hud.hide(animated: false)
        }
        self.h3wqTp4QEDNi67J0()
        super.clFi25NuDNbscWXL()
    }
    
    func h3wqTp4QEDNi67J0(){
        if let retryview =  self.yDCfMxMjoZSqnqxo{
            for childview in retryview.subviews{
                childview.removeFromSuperview()
            }
            retryview.removeFromSuperview()
        }
        self.yDCfMxMjoZSqnqxo = nil
    }
    
    func dnOwhBpbw9jbgRH7(){
        let topSpace = UIDevice.qianli_statusbar_and_navibar_height()
        if(self.yDCfMxMjoZSqnqxo == nil){
            self.yDCfMxMjoZSqnqxo = RetryNet(frame: CGRect(x: 0, y: topSpace+5.0, width: qianli_pm_width, height: qianli_pm_height-topSpace-5.0))
            if let retryview = self.yDCfMxMjoZSqnqxo{
                self.view.addSubview(retryview)
                retryview.tapBlock = { [weak self] in
                    self?.yeUFPjBQnL6UZxSA()
                }
            }
        }
    }
    
    // 设置上拉加载更多的 footer
    private func gZk5cuoJMRAV2npo() {
        let footer = UIView(frame: CGRect(x: 0, y: 0, width: inviteTable.bounds.width, height: 50))
        self.RF7NlUOk3CS8x58m.text = _iPageNum>=_iPageTotal ? "- \(LocalizedString("No More")) -" : LocalizedString("Pull up to load more")
        self.RF7NlUOk3CS8x58m.textAlignment = .center
        self.RF7NlUOk3CS8x58m.textColor = .secondaryLabel
        self.RF7NlUOk3CS8x58m.frame = CGRect(x: footer.bounds.width/2 - 100, y: 20, width: 200, height: 30)
        footer.addSubview(self.RF7NlUOk3CS8x58m)
        self.RF7NlUOk3CS8x58m.isHidden = true

        self.brzwDc3ZHa8Rmucg.frame = CGRect(x: footer.bounds.width/2 - 30/2 - 70, y: 20, width: 30, height: 30)
        footer.addSubview(self.brzwDc3ZHa8Rmucg)
        self.brzwDc3ZHa8Rmucg.color = .label
        inviteTable.tableFooterView = footer
    }
    
    @objc func yeUFPjBQnL6UZxSA(){
        self.qbYzOWtOn9x9CQkk = true
        self.M62h1bVOydwY8i4y(LocalizedString("Loading, please wait..."))
//        loadingHud = MBProgressHUD.showAdded(to: self.view, animated: true) //简单加载指示器也可以直接UIActivityIndicatorView来代替
//        if let loadingHud = loadingHud{
//            loadingHud.label.text = LocalizedString("Loading, please wait...")//"正在加载,请稍候..."
//        }
        UserInfoViewModel.shared.AK7x06pAg9dXtdB1(pagination: Pagination(orderBy: "id DESC", pageNum: _iPageNum, pageSize: 50))
        UserInfoViewModel.shared.completionMsgHandler = {[weak self](result,msg) in
            DispatchQueue.main.async {
                if let self=self{
                    self.pxKiSZFNBBoSMWU3.endRefreshing()
                    self.l0JOXR3PG9RznwqZ()
                    self.KBqIKQ9HAzT2WzdD(msg)
                }
            }
        }
    }
    
    @objc func mhMtQtSTyofwGqyE(){
        self.qbYzOWtOn9x9CQkk = true
        _iPageNum = 1
        UserInfoViewModel.shared.AK7x06pAg9dXtdB1(pagination: Pagination(orderBy: "id DESC", pageNum: _iPageNum, pageSize: 50))
        UserInfoViewModel.shared.completionMsgHandler = {[weak self](result,msg) in
            DispatchQueue.main.async {
                if let self=self{
                    self.pxKiSZFNBBoSMWU3.endRefreshing()
                    self.l0JOXR3PG9RznwqZ()
                    self.KBqIKQ9HAzT2WzdD(msg)
                }
            }
        }
    }
    
 
    private func WiolLzCiaV0Lkpz0() {
        if (_iPageNum>=_iPageTotal){
            self.X4MlDl1WbtyrOkzs = false
            self.RF7NlUOk3CS8x58m.text = "- \(LocalizedString("No More")) -"
            return
        }
        _iPageNum += 1
        guard !self.X4MlDl1WbtyrOkzs else { return }
        
        self.X4MlDl1WbtyrOkzs = true
        self.RF7NlUOk3CS8x58m.text = LocalizedString("Loading...") //"正在加载..."
        self.brzwDc3ZHa8Rmucg.startAnimating()

        // 模拟加载更多数据
        DispatchQueue.global().async {
            sleep(2)
            DispatchQueue.main.async {
                self.X4MlDl1WbtyrOkzs = false
                self.RF7NlUOk3CS8x58m.text = LocalizedString("Pull up to load more")
                self.brzwDc3ZHa8Rmucg.stopAnimating()
                // 这里可以添加加载更多数据的逻辑
            }
        }
    }
    
    func KBqIKQ9HAzT2WzdD(_ result:String){
        if(result.isEmpty){
            if let inviteData = UserInfoViewModel.shared.inviteDurationData{
                _iPageTotal = inviteData.total
                if (inviteData.total>0){
                    if let myInviteList = inviteData.data{
                        if(_iPageNum==1){
                            self.SC6UBWD47fXYWAU3 = myInviteList
                        }else{
                            self.SC6UBWD47fXYWAU3.append(contentsOf: myInviteList)
                        }
                        if(self.SC6UBWD47fXYWAU3.count>0){
                            self.RF7NlUOk3CS8x58m.isHidden = false
                            self.RF7NlUOk3CS8x58m.text = _iPageNum>=_iPageTotal ? "- \(LocalizedString("No More")) -" : LocalizedString("Pull up to load more")
                        }
                        self.inviteTable.reloadData()
                        self.h3wqTp4QEDNi67J0()
                        return
                    }
                }
            }
//数据为空
            dnOwhBpbw9jbgRH7()
            if let rtview = self.yDCfMxMjoZSqnqxo{
                rtview.vSXenwySp9gyesbp(LocalizedString("Invitation is Null"))//"当前还没有邀请数据"
                rtview.d770kqK5BHcHWehm(1)
            }
        }else{
//读取失败，retry
            self.RF7NlUOk3CS8x58m.isHidden = true
            let hud = MBProgressHUD.showAdded(to: view, animated: true)
            hud.mode = .text
            hud.label.text = result
            hud.hide(animated: true, afterDelay: 1.0) // 2 秒后自动消失

            dnOwhBpbw9jbgRH7()
            if let rtview = self.yDCfMxMjoZSqnqxo{
                rtview.vSXenwySp9gyesbp(LocalizedString("Load Failed. Please check network & try again!"))
                rtview.d770kqK5BHcHWehm(0)
            }
        }
        
        self.inviteTable.reloadData()
    }

}

extension QianliInviteDetail:UITableViewDelegate, UITableViewDataSource{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y
        let contentHeight = scrollView.contentSize.height
        let height = scrollView.frame.height

        if offsetY > contentHeight - height {
            WiolLzCiaV0Lkpz0()
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.SC6UBWD47fXYWAU3.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "InviteDurationCell") as? InviteDurationCell//从缓存池中取
        if nil == cell{//如缓存池中没取到，则创建
            cell = UITableViewCell.init(style: .default, reuseIdentifier: "InviteDurationCell") as? InviteDurationCell
        }
       
        cell!.c612AWlbhGInRMY3(info: self.SC6UBWD47fXYWAU3[indexPath.row])
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //直接点击为运行测试该项
        QianliVibrateEnum.selection.vibrate()
//选择对应节点，并切换？
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100.0
    }
}
